const React = require('react');
const ReactDOM = require('react-dom');

class TodoApp extends React.Component {
    constructor(props) {
        super(props);
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.state = {items: [], text: ''};
    }

    render() {
        return (
            <div>
                <h3>ToDo</h3>
                <TodoList items={this.state.items}/>
                <form onSubmit={this.handleSubmit}>
                    <input type="text" onChange={this.handleChange} value={this.state.text}/>
                    <button>{'ADD #' + (this.state.items.length + 1)}</button>
                </form>
            </div>
        );
    }

    handleChange(e){
        this.setState({text:e.target.value});
    };
    handleSubmit(e){
        e.preventDefault();
        var newItem={
            text:this.state.text,
            id:Date.now()
        };
        this.setState((prev)=>({
            items:prev.items.concat(newItem),
            text:''
        }))
    };
}

class TodoList extends React.Component{
    render(){
        return(
            <ul>
                {this.props.items.map((item)=>
                (<li key={item.id}>{item.text}</li>)
            )}
            </ul>
        );
    }
}

ReactDOM.render(<TodoApp/>, document.getElementById('page'));